package com.woniu.order.service.consumer;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.order.common.enums.OrderStatusEnum;
import com.woniu.order.infra.config.AlipayConfig;
import com.woniu.order.infra.model.Order;
import com.woniu.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
@RocketMQMessageListener(topic = "lxlg-find-pay",consumerGroup = "lxlg-find-pay")
public class OrderPayFindConsuer implements RocketMQListener<String>{
	
	@Resource
	private OrderService orderService;
	
	private ObjectMapper om = new ObjectMapper();
	
	@Override
	public void onMessage(String message) {
		log.info("支付回查");
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
				AlipayConfig.sign_type);
		AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
		//请求接口
		alipayRequest.setBizContent("{\"out_trade_no\":\"" + message + "\"," + "\"trade_no\":\"" + "" + "\"}");
		//转换格式
		String result = "";
		try {
			result = alipayClient.execute(alipayRequest).getBody();
			Map<String, Map<String, String>> maps = om.readValue(result, Map.class);
			Map<String, String> date = maps.get("alipay_trade_query_response");
			String state = date.get("trade_status");
			String orderNum = date.get("out_trade_no");
			if (state != null && state.equals("TRADE_SUCCESS")) {
				log.info("查询到订单支付成功");
				log.info("查看支付逻辑是否处理");
				Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_num", orderNum));
				if(!order.getOrderState().equals(OrderStatusEnum.PAID.getCode())) {
					log.info("执行支付以后的逻辑");
					orderService.setPayOk(order.getOrderId());
				} else {
					log.info("不处理");
				}
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
	}

} 
